{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tool Search with Embeddings: Scaling Claude to Thousands of Tools\n",
    "\n",
    "Building Claude applications with dozens of specialized tools quickly hits a wall: providing all tool definitions upfront consumes your context window, increases latency and costs, and makes it harder for Claude to find the right tool. Beyond ~100 tools, this approach becomes impractical.\n",
    "\n",
    "Semantic tool search solves this by treating tools as discoverable resources. Instead of front-loading hundreds of definitions, you give Claude a single `tool_search` tool that returns relevant capabilities on demand, cutting context usage by 90%+ while enabling applications that scale to thousands of tools.\n",
    "\n",
    "**By the end of this cookbook, you'll be able to:**\n",
    "- Implement client-side tool search to scale Claude applications from dozens to thousands of tools\n",
    "- Use semantic embeddings to dynamically discover relevant tools based on task context\n",
    "- Apply this pattern to domain-specific tool libraries (APIs, databases, internal systems)\n",
    "\n",
    "This pattern is used in production by teams managing large tool ecosystems where context efficiency is critical. While we'll demonstrate with a small set of tools for clarity, the same approach scales seamlessly to libraries with hundreds or thousands of tools.\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "Before following this guide, ensure you have:\n",
    "\n",
    "**Required Knowledge**\n",
    "- Python fundamentals - comfortable with functions, dictionaries, and basic data structures\n",
    "- Basic understanding of Claude tool use - we recommend reading the [Tool Use Guide](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) first\n",
    "\n",
    "**Required Tools**\n",
    "- Python 3.11 or higher\n",
    "- Anthropic API key ([get one here](https://docs.anthropic.com/claude/reference/getting-started-with-the-api))\n",
    "\n",
    "## Setup\n",
    "\n",
    "First, install the required dependencies:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
      "To disable this warning, you can either:\n",
      "\t- Avoid using `tokenizers` before the fork if possible\n",
      "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "# Note: we use -q to avoid printing too much to stdout\n",
    "# Use --only-binary to avoid build issues with pythran\n",
    "%pip install --only-binary :all: -q anthropic sentence-transformers numpy python-dotenv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ensure your `.env` file contains:\n",
    "```\n",
    "ANTHROPIC_API_KEY=your_key_here\n",
    "```\n",
    "\n",
    "Load your environment variables and configure the client:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading SentenceTransformer model...\n",
      "✓ Clients initialized successfully\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import random\n",
    "from datetime import datetime, timedelta\n",
    "from typing import Any\n",
    "\n",
    "import anthropic\n",
    "import numpy as np\n",
    "from dotenv import load_dotenv\n",
    "from sentence_transformers import SentenceTransformer\n",
    "\n",
    "# Load environment variables from .env file\n",
    "load_dotenv()\n",
    "\n",
    "# Define model constant for easy updates\n",
    "MODEL = \"claude-sonnet-4-5-20250929\"\n",
    "\n",
    "# Initialize Claude client (API key loaded from environment)\n",
    "claude_client = anthropic.Anthropic()\n",
    "\n",
    "# Load the SentenceTransformer model\n",
    "# all-MiniLM-L6-v2 is a lightweight model with 384 dimensional embeddings\n",
    "# It will be downloaded from HuggingFace on first use\n",
    "print(\"Loading SentenceTransformer model...\")\n",
    "embedding_model = SentenceTransformer(\"sentence-transformers/all-MiniLM-L6-v2\")\n",
    "\n",
    "print(\"✓ Clients initialized successfully\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define Tool Library\n",
    "\n",
    "Before we can implement semantic search, we need tools to search through. We'll create a library of 8 tools across two categories: Weather and Finance.\n",
    "\n",
    "In production applications, you might manage hundreds or thousands of tools across your internal APIs, database operations, or third-party integrations. The semantic search approach scales to these larger libraries without modification - we're using a small set here purely for demonstration clarity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✓ Defined 8 tools in the library\n"
     ]
    }
   ],
   "source": [
    "# Define our tool library with 2 domains\n",
    "TOOL_LIBRARY = [\n",
    "    # Weather Tools\n",
    "    {\n",
    "        \"name\": \"get_weather\",\n",
    "        \"description\": \"Get the current weather in a given location\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"location\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"The city and state, e.g. San Francisco, CA\",\n",
    "                },\n",
    "                \"unit\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"enum\": [\"celsius\", \"fahrenheit\"],\n",
    "                    \"description\": \"The unit of temperature\",\n",
    "                },\n",
    "            },\n",
    "            \"required\": [\"location\"],\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"get_forecast\",\n",
    "        \"description\": \"Get the weather forecast for multiple days ahead\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"location\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"The city and state\",\n",
    "                },\n",
    "                \"days\": {\n",
    "                    \"type\": \"number\",\n",
    "                    \"description\": \"Number of days to forecast (1-10)\",\n",
    "                },\n",
    "            },\n",
    "            \"required\": [\"location\", \"days\"],\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"get_timezone\",\n",
    "        \"description\": \"Get the current timezone and time for a location\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"location\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"City name or timezone identifier\",\n",
    "                }\n",
    "            },\n",
    "            \"required\": [\"location\"],\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"get_air_quality\",\n",
    "        \"description\": \"Get current air quality index and pollutant levels for a location\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"location\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"City name or coordinates\",\n",
    "                }\n",
    "            },\n",
    "            \"required\": [\"location\"],\n",
    "        },\n",
    "    },\n",
    "    # Finance Tools\n",
    "    {\n",
    "        \"name\": \"get_stock_price\",\n",
    "        \"description\": \"Get the current stock price and market data for a given ticker symbol\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"ticker\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"Stock ticker symbol (e.g., AAPL, GOOGL)\",\n",
    "                },\n",
    "                \"include_history\": {\n",
    "                    \"type\": \"boolean\",\n",
    "                    \"description\": \"Include historical data\",\n",
    "                },\n",
    "            },\n",
    "            \"required\": [\"ticker\"],\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"convert_currency\",\n",
    "        \"description\": \"Convert an amount from one currency to another using current exchange rates\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"amount\": {\n",
    "                    \"type\": \"number\",\n",
    "                    \"description\": \"Amount to convert\",\n",
    "                },\n",
    "                \"from_currency\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"Source currency code (e.g., USD)\",\n",
    "                },\n",
    "                \"to_currency\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"Target currency code (e.g., EUR)\",\n",
    "                },\n",
    "            },\n",
    "            \"required\": [\"amount\", \"from_currency\", \"to_currency\"],\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"calculate_compound_interest\",\n",
    "        \"description\": \"Calculate compound interest for investments over time\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"principal\": {\n",
    "                    \"type\": \"number\",\n",
    "                    \"description\": \"Initial investment amount\",\n",
    "                },\n",
    "                \"rate\": {\n",
    "                    \"type\": \"number\",\n",
    "                    \"description\": \"Annual interest rate (as percentage)\",\n",
    "                },\n",
    "                \"years\": {\"type\": \"number\", \"description\": \"Number of years\"},\n",
    "                \"frequency\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"enum\": [\"daily\", \"monthly\", \"quarterly\", \"annually\"],\n",
    "                    \"description\": \"Compounding frequency\",\n",
    "                },\n",
    "            },\n",
    "            \"required\": [\"principal\", \"rate\", \"years\"],\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"get_market_news\",\n",
    "        \"description\": \"Get recent financial news and market updates for a specific company or sector\",\n",
    "        \"input_schema\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"query\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"Company name, ticker symbol, or sector\",\n",
    "                },\n",
    "                \"limit\": {\n",
    "                    \"type\": \"number\",\n",
    "                    \"description\": \"Maximum number of news articles to return\",\n",
    "                },\n",
    "            },\n",
    "            \"required\": [\"query\"],\n",
    "        },\n",
    "    },\n",
    "]\n",
    "\n",
    "print(f\"✓ Defined {len(TOOL_LIBRARY)} tools in the library\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create Tool Embeddings\n",
    "\n",
    "Semantic search works by comparing the *meaning* of text, rather than just searching for keywords. To enable this, we need to convert each tool definition into an **embedding vector** that captures its semantic meaning.\n",
    "\n",
    "Since our tool definitions are structured JSON objects with names, descriptions, and parameters, we first convert each tool into a human-readable text representation, then generate embedding vectors using SentenceTransformer's `all-MiniLM-L6-v2` model.\n",
    "\n",
    "We picked this model because it is:\n",
    "- **Lightweight and fast** (only 384 dimensions vs 768+ for larger models)\n",
    "- **Runs locally** without requiring API calls\n",
    "- **Sufficient for tool search** (you can experiment with larger models for better accuracy)\n",
    "\n",
    "Let's start by creating a function that converts tool definitions into searchable text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample tool text representation:\n",
      "Tool: get_weather\n",
      "Description: Get the current weather in a given location\n",
      "Parameters: location (string): The city and state, e.g. San Francisco, CA, unit (string): The unit of temperature\n"
     ]
    }
   ],
   "source": [
    "def tool_to_text(tool: dict[str, Any]) -> str:\n",
    "    \"\"\"\n",
    "    Convert a tool definition into a text representation for embedding.\n",
    "    Combines the tool name, description, and parameter information.\n",
    "    \"\"\"\n",
    "    text_parts = [\n",
    "        f\"Tool: {tool['name']}\",\n",
    "        f\"Description: {tool['description']}\",\n",
    "    ]\n",
    "\n",
    "    # Add parameter information\n",
    "    if \"input_schema\" in tool and \"properties\" in tool[\"input_schema\"]:\n",
    "        params = tool[\"input_schema\"][\"properties\"]\n",
    "        param_descriptions = []\n",
    "        for param_name, param_info in params.items():\n",
    "            param_desc = param_info.get(\"description\", \"\")\n",
    "            param_type = param_info.get(\"type\", \"\")\n",
    "            param_descriptions.append(f\"{param_name} ({param_type}): {param_desc}\")\n",
    "\n",
    "        if param_descriptions:\n",
    "            text_parts.append(\"Parameters: \" + \", \".join(param_descriptions))\n",
    "\n",
    "    return \"\\n\".join(text_parts)\n",
    "\n",
    "\n",
    "# Test with one tool\n",
    "sample_text = tool_to_text(TOOL_LIBRARY[0])\n",
    "print(\"Sample tool text representation:\")\n",
    "print(sample_text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's create embeddings for all our tools:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Creating embeddings for all tools...\n",
      "✓ Created embeddings with shape: (8, 384)\n",
      "  - 8 tools\n",
      "  - 384 dimensions per embedding\n"
     ]
    }
   ],
   "source": [
    "# Create embeddings for all tools\n",
    "print(\"Creating embeddings for all tools...\")\n",
    "\n",
    "tool_texts = [tool_to_text(tool) for tool in TOOL_LIBRARY]\n",
    "\n",
    "# Embed all tools at once using SentenceTransformer\n",
    "# The model returns normalized embeddings by default\n",
    "tool_embeddings = embedding_model.encode(tool_texts, convert_to_numpy=True)\n",
    "\n",
    "print(f\"✓ Created embeddings with shape: {tool_embeddings.shape}\")\n",
    "print(f\"  - {tool_embeddings.shape[0]} tools\")\n",
    "print(f\"  - {tool_embeddings.shape[1]} dimensions per embedding\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Implement Tool Search\n",
    "\n",
    "With our tools embedded as vectors, we can now implement semantic search. If two pieces of text have similar meanings, their embedding vectors will be close together in vector space. We measure this \"closeness\" using **cosine similarity**.\n",
    "\n",
    "The search process:\n",
    "1. **Embed the query**: Convert Claude's natural language search request into the same vector space as our tools\n",
    "2. **Calculate similarity**: Compute cosine similarity between the query vector and each tool vector\n",
    "3. **Rank and return**: Sort tools by similarity score and return the top N matches\n",
    "\n",
    "With semantic search, Claude can search using natural language like \"I need to check the weather\" or \"calculate investment returns\" rather than exact tool names.\n",
    "\n",
    "Let's implement the search function and test it with a sample query:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Search query: 'I need to check the weather'\n",
      "\n",
      "Top 3 matching tools:\n",
      "1. get_weather (similarity: 0.560)\n",
      "2. get_forecast (similarity: 0.508)\n",
      "3. get_air_quality (similarity: 0.401)\n"
     ]
    }
   ],
   "source": [
    "def search_tools(query: str, top_k: int = 5) -> list[dict[str, Any]]:\n",
    "    \"\"\"\n",
    "    Search for tools using semantic similarity.\n",
    "\n",
    "    Args:\n",
    "        query: Natural language description of what tool is needed\n",
    "        top_k: Number of top tools to return\n",
    "\n",
    "    Returns:\n",
    "        List of tool definitions most relevant to the query\n",
    "    \"\"\"\n",
    "    # Embed the query using SentenceTransformer\n",
    "    query_embedding = embedding_model.encode(query, convert_to_numpy=True)\n",
    "\n",
    "    # Calculate cosine similarity using dot product\n",
    "    # SentenceTransformer returns normalized embeddings, so dot product = cosine similarity\n",
    "    similarities = np.dot(tool_embeddings, query_embedding)\n",
    "\n",
    "    # Get top k indices\n",
    "    top_indices = np.argsort(similarities)[-top_k:][::-1]\n",
    "\n",
    "    # Return the corresponding tools with their scores\n",
    "    results = []\n",
    "    for idx in top_indices:\n",
    "        results.append({\"tool\": TOOL_LIBRARY[idx], \"similarity_score\": float(similarities[idx])})\n",
    "\n",
    "    return results\n",
    "\n",
    "\n",
    "# Test the search function\n",
    "test_query = \"I need to check the weather\"\n",
    "test_results = search_tools(test_query, top_k=3)\n",
    "\n",
    "print(f\"Search query: '{test_query}'\\n\")\n",
    "print(\"Top 3 matching tools:\")\n",
    "for i, result in enumerate(test_results, 1):\n",
    "    tool_name = result[\"tool\"][\"name\"]\n",
    "    score = result[\"similarity_score\"]\n",
    "    print(f\"{i}. {tool_name} (similarity: {score:.3f})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define the tool_search Tool\n",
    "\n",
    "Now we'll implement the **meta-tool** that allows Claude to discover other tools on demand. When Claude needs a capability it doesn't have, it searches for it using this `tool_search` tool, receives the tool definitions in the result, and can use those newly discovered tools immediately.\n",
    "\n",
    "This is the only tool we provide to Claude initially:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✓ Tool search definition created\n"
     ]
    }
   ],
   "source": [
    "# The tool_search tool definition\n",
    "TOOL_SEARCH_DEFINITION = {\n",
    "    \"name\": \"tool_search\",\n",
    "    \"description\": \"Search for available tools that can help with a task. Returns tool definitions for matching tools. Use this when you need a tool but don't have it available yet.\",\n",
    "    \"input_schema\": {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "            \"query\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"Natural language description of what kind of tool you need (e.g., 'weather information', 'currency conversion', 'stock prices')\",\n",
    "            },\n",
    "            \"top_k\": {\n",
    "                \"type\": \"number\",\n",
    "                \"description\": \"Number of tools to return (default: 5)\",\n",
    "            },\n",
    "        },\n",
    "        \"required\": [\"query\"],\n",
    "    },\n",
    "}\n",
    "\n",
    "print(\"✓ Tool search definition created\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's implement the handler that processes `tool_search` calls from Claude and returns discovered tools:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "🔍 Tool search: 'stock market data'\n",
      "   Found 3 tools:\n",
      "   1. get_stock_price (similarity: 0.524)\n",
      "   2. get_market_news (similarity: 0.469)\n",
      "   3. calculate_compound_interest (similarity: 0.244)\n",
      "\n",
      "Returned 3 tool references:\n",
      "  {'type': 'tool_reference', 'tool_name': 'get_stock_price'}\n",
      "  {'type': 'tool_reference', 'tool_name': 'get_market_news'}\n",
      "  {'type': 'tool_reference', 'tool_name': 'calculate_compound_interest'}\n"
     ]
    }
   ],
   "source": [
    "def handle_tool_search(query: str, top_k: int = 5) -> list[dict[str, Any]]:\n",
    "    \"\"\"\n",
    "    Handle a tool_search invocation and return tool references.\n",
    "\n",
    "    Returns a list of tool_reference content blocks for discovered tools.\n",
    "    \"\"\"\n",
    "    # Search for relevant tools\n",
    "    results = search_tools(query, top_k=top_k)\n",
    "\n",
    "    # Create tool_reference objects instead of full definitions\n",
    "    tool_references = [\n",
    "        {\"type\": \"tool_reference\", \"tool_name\": result[\"tool\"][\"name\"]} for result in results\n",
    "    ]\n",
    "\n",
    "    print(f\"\\n🔍 Tool search: '{query}'\")\n",
    "    print(f\"   Found {len(tool_references)} tools:\")\n",
    "    for i, result in enumerate(results, 1):\n",
    "        print(f\"   {i}. {result['tool']['name']} (similarity: {result['similarity_score']:.3f})\")\n",
    "\n",
    "    return tool_references\n",
    "\n",
    "\n",
    "# Test the handler\n",
    "test_result = handle_tool_search(\"stock market data\", top_k=3)\n",
    "print(f\"\\nReturned {len(test_result)} tool references:\")\n",
    "for ref in test_result:\n",
    "    print(f\"  {ref}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mock Tool Execution\n",
    "\n",
    "For this demonstration, we'll create mock responses for tool executions. In a real application, these would call actual APIs or services:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✓ Mock tool execution function created\n"
     ]
    }
   ],
   "source": [
    "def mock_tool_execution(tool_name: str, tool_input: dict[str, Any]) -> str:\n",
    "    \"\"\"\n",
    "    Generate realistic mock responses for tool executions.\n",
    "\n",
    "    Args:\n",
    "        tool_name: Name of the tool being executed\n",
    "        tool_input: Input parameters for the tool\n",
    "\n",
    "    Returns:\n",
    "        Mock response string appropriate for the tool\n",
    "    \"\"\"\n",
    "    # Weather tools\n",
    "    if tool_name == \"get_weather\":\n",
    "        location = tool_input.get(\"location\", \"Unknown\")\n",
    "        unit = tool_input.get(\"unit\", \"fahrenheit\")\n",
    "        temp = random.randint(15, 30) if unit == \"celsius\" else random.randint(60, 85)\n",
    "        conditions = random.choice([\"sunny\", \"partly cloudy\", \"cloudy\", \"rainy\"])\n",
    "        return json.dumps(\n",
    "            {\n",
    "                \"location\": location,\n",
    "                \"temperature\": temp,\n",
    "                \"unit\": unit,\n",
    "                \"conditions\": conditions,\n",
    "                \"humidity\": random.randint(40, 80),\n",
    "                \"wind_speed\": random.randint(5, 20),\n",
    "            }\n",
    "        )\n",
    "\n",
    "    elif tool_name == \"get_forecast\":\n",
    "        location = tool_input.get(\"location\", \"Unknown\")\n",
    "        days = int(tool_input.get(\"days\", 5))\n",
    "        forecast = []\n",
    "        for i in range(days):\n",
    "            date = (datetime.now() + timedelta(days=i)).strftime(\"%Y-%m-%d\")\n",
    "            forecast.append(\n",
    "                {\n",
    "                    \"date\": date,\n",
    "                    \"high\": random.randint(20, 30),\n",
    "                    \"low\": random.randint(10, 20),\n",
    "                    \"conditions\": random.choice([\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"]),\n",
    "                }\n",
    "            )\n",
    "        return json.dumps({\"location\": location, \"forecast\": forecast})\n",
    "\n",
    "    elif tool_name == \"get_timezone\":\n",
    "        location = tool_input.get(\"location\", \"Unknown\")\n",
    "        return json.dumps(\n",
    "            {\n",
    "                \"location\": location,\n",
    "                \"timezone\": \"UTC+9\",\n",
    "                \"current_time\": datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n",
    "                \"utc_offset\": \"+09:00\",\n",
    "            }\n",
    "        )\n",
    "\n",
    "    elif tool_name == \"get_air_quality\":\n",
    "        location = tool_input.get(\"location\", \"Unknown\")\n",
    "        aqi = random.randint(20, 150)\n",
    "        categories = {\n",
    "            (0, 50): \"Good\",\n",
    "            (51, 100): \"Moderate\",\n",
    "            (101, 150): \"Unhealthy for Sensitive Groups\",\n",
    "        }\n",
    "        category = next(cat for (low, high), cat in categories.items() if low <= aqi <= high)\n",
    "        return json.dumps(\n",
    "            {\n",
    "                \"location\": location,\n",
    "                \"aqi\": aqi,\n",
    "                \"category\": category,\n",
    "                \"pollutants\": {\n",
    "                    \"pm25\": random.randint(5, 50),\n",
    "                    \"pm10\": random.randint(10, 100),\n",
    "                    \"o3\": random.randint(20, 80),\n",
    "                },\n",
    "            }\n",
    "        )\n",
    "\n",
    "    # Finance tools\n",
    "    elif tool_name == \"get_stock_price\":\n",
    "        ticker = tool_input.get(\"ticker\", \"UNKNOWN\")\n",
    "        return json.dumps(\n",
    "            {\n",
    "                \"ticker\": ticker,\n",
    "                \"price\": round(random.uniform(100, 500), 2),\n",
    "                \"change\": round(random.uniform(-5, 5), 2),\n",
    "                \"change_percent\": round(random.uniform(-2, 2), 2),\n",
    "                \"volume\": random.randint(1000000, 10000000),\n",
    "                \"market_cap\": f\"${random.randint(100, 1000)}B\",\n",
    "            }\n",
    "        )\n",
    "\n",
    "    elif tool_name == \"convert_currency\":\n",
    "        amount = tool_input.get(\"amount\", 0)\n",
    "        from_currency = tool_input.get(\"from_currency\", \"USD\")\n",
    "        to_currency = tool_input.get(\"to_currency\", \"EUR\")\n",
    "        # Mock exchange rate\n",
    "        rate = random.uniform(0.8, 1.2)\n",
    "        converted = round(amount * rate, 2)\n",
    "        return json.dumps(\n",
    "            {\n",
    "                \"original_amount\": amount,\n",
    "                \"from_currency\": from_currency,\n",
    "                \"to_currency\": to_currency,\n",
    "                \"exchange_rate\": round(rate, 4),\n",
    "                \"converted_amount\": converted,\n",
    "            }\n",
    "        )\n",
    "\n",
    "    elif tool_name == \"calculate_compound_interest\":\n",
    "        principal = tool_input.get(\"principal\", 0)\n",
    "        rate = tool_input.get(\"rate\", 0)\n",
    "        years = tool_input.get(\"years\", 0)\n",
    "        frequency = tool_input.get(\"frequency\", \"monthly\")\n",
    "\n",
    "        # Calculate compound interest\n",
    "        n_map = {\"daily\": 365, \"monthly\": 12, \"quarterly\": 4, \"annually\": 1}\n",
    "        n = n_map.get(frequency, 12)\n",
    "        final_amount = principal * (1 + rate / 100 / n) ** (n * years)\n",
    "        interest_earned = final_amount - principal\n",
    "\n",
    "        return json.dumps(\n",
    "            {\n",
    "                \"principal\": principal,\n",
    "                \"rate\": rate,\n",
    "                \"years\": years,\n",
    "                \"compounding_frequency\": frequency,\n",
    "                \"final_amount\": round(final_amount, 2),\n",
    "                \"interest_earned\": round(interest_earned, 2),\n",
    "            }\n",
    "        )\n",
    "\n",
    "    elif tool_name == \"get_market_news\":\n",
    "        query = tool_input.get(\"query\", \"\")\n",
    "        limit = tool_input.get(\"limit\", 5)\n",
    "        news = []\n",
    "        for i in range(min(limit, 5)):\n",
    "            news.append(\n",
    "                {\n",
    "                    \"title\": f\"{query} - News Article {i + 1}\",\n",
    "                    \"source\": random.choice(\n",
    "                        [\n",
    "                            \"Bloomberg\",\n",
    "                            \"Reuters\",\n",
    "                            \"Financial Times\",\n",
    "                            \"Wall Street Journal\",\n",
    "                        ]\n",
    "                    ),\n",
    "                    \"published\": (datetime.now() - timedelta(hours=random.randint(1, 24))).strftime(\n",
    "                        \"%Y-%m-%d %H:%M\"\n",
    "                    ),\n",
    "                    \"summary\": f\"Latest developments regarding {query}...\",\n",
    "                }\n",
    "            )\n",
    "        return json.dumps({\"query\": query, \"articles\": news, \"count\": len(news)})\n",
    "\n",
    "    # Default fallback\n",
    "    else:\n",
    "        return json.dumps(\n",
    "            {\n",
    "                \"status\": \"executed\",\n",
    "                \"tool\": tool_name,\n",
    "                \"message\": f\"Tool {tool_name} executed successfully with input: {json.dumps(tool_input)}\",\n",
    "            }\n",
    "        )\n",
    "\n",
    "\n",
    "print(\"✓ Mock tool execution function created\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Implement Conversation Loop\n",
    "\n",
    "Now let's put it all together! We'll create a conversation loop that handles the complete tool search workflow.\n",
    "\n",
    "**The conversation flow:**\n",
    "1. Claude starts with only the `tool_search` tool available\n",
    "2. When Claude calls `tool_search`, we run semantic search and return matching tool definitions\n",
    "3. Claude can then use the discovered tools immediately\n",
    "4. When Claude calls a discovered tool, we execute it (using mock responses for this demo)\n",
    "5. The loop continues until Claude has a final answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✓ Conversation loop implemented\n"
     ]
    }
   ],
   "source": [
    "def run_tool_search_conversation(user_message: str, max_turns: int = 5) -> None:\n",
    "    \"\"\"\n",
    "    Run a conversation with Claude using the tool search pattern.\n",
    "\n",
    "    Args:\n",
    "        user_message: The initial user message\n",
    "        max_turns: Maximum number of conversation turns\n",
    "    \"\"\"\n",
    "    print(f\"\\n{'=' * 80}\")\n",
    "    print(f\"USER: {user_message}\")\n",
    "    print(f\"{'=' * 80}\\n\")\n",
    "\n",
    "    # Initialize conversation with only tool_search available\n",
    "    messages = [{\"role\": \"user\", \"content\": user_message}]\n",
    "\n",
    "    for turn in range(max_turns):\n",
    "        print(f\"\\n--- Turn {turn + 1} ---\")\n",
    "\n",
    "        # Call Claude with current message history\n",
    "        response = claude_client.messages.create(\n",
    "            model=MODEL,\n",
    "            max_tokens=1024,\n",
    "            tools=TOOL_LIBRARY + [TOOL_SEARCH_DEFINITION],\n",
    "            messages=messages,\n",
    "            # IMPORTANT: This beta header enables tool definitions in tool results\n",
    "            extra_headers={\"anthropic-beta\": \"advanced-tool-use-2025-11-20\"},\n",
    "        )\n",
    "\n",
    "        # Add assistant's response to messages\n",
    "        messages.append({\"role\": \"assistant\", \"content\": response.content})\n",
    "\n",
    "        # Check if we're done\n",
    "        if response.stop_reason == \"end_turn\":\n",
    "            print(\"\\n✓ Conversation complete\\n\")\n",
    "            # Print final response\n",
    "            for block in response.content:\n",
    "                if block.type == \"text\":\n",
    "                    print(f\"ASSISTANT: {block.text}\")\n",
    "            break\n",
    "\n",
    "        # Handle tool uses\n",
    "        if response.stop_reason == \"tool_use\":\n",
    "            tool_results = []\n",
    "\n",
    "            for block in response.content:\n",
    "                if block.type == \"text\":\n",
    "                    print(f\"\\nASSISTANT: {block.text}\")\n",
    "\n",
    "                elif block.type == \"tool_use\":\n",
    "                    tool_name = block.name\n",
    "                    tool_input = block.input\n",
    "                    tool_use_id = block.id\n",
    "\n",
    "                    print(f\"\\n🔧 Tool invocation: {tool_name}\")\n",
    "                    print(f\"   Input: {json.dumps(tool_input, indent=2)}\")\n",
    "\n",
    "                    if tool_name == \"tool_search\":\n",
    "                        # Handle tool search\n",
    "                        query = tool_input[\"query\"]\n",
    "                        top_k = tool_input.get(\"top_k\", 5)\n",
    "\n",
    "                        # Get tool references\n",
    "                        tool_references = handle_tool_search(query, top_k)\n",
    "\n",
    "                        # Create tool result with tool_reference content blocks\n",
    "                        tool_results.append(\n",
    "                            {\n",
    "                                \"type\": \"tool_result\",\n",
    "                                \"tool_use_id\": tool_use_id,\n",
    "                                \"content\": tool_references,\n",
    "                            }\n",
    "                        )\n",
    "                    else:\n",
    "                        # Execute the discovered tool with mock data\n",
    "                        mock_result = mock_tool_execution(tool_name, tool_input)\n",
    "\n",
    "                        # Print a preview of the result\n",
    "                        if len(mock_result) > 150:\n",
    "                            print(f\"   ✅ Mock result: {mock_result[:150]}...\")\n",
    "                        else:\n",
    "                            print(f\"   ✅ Mock result: {mock_result}\")\n",
    "\n",
    "                        tool_results.append(\n",
    "                            {\n",
    "                                \"type\": \"tool_result\",\n",
    "                                \"tool_use_id\": tool_use_id,\n",
    "                                \"content\": mock_result,\n",
    "                            }\n",
    "                        )\n",
    "\n",
    "            # Add tool results to messages\n",
    "            if tool_results:\n",
    "                messages.append({\"role\": \"user\", \"content\": tool_results})\n",
    "        else:\n",
    "            print(f\"\\nUnexpected stop reason: {response.stop_reason}\")\n",
    "            break\n",
    "\n",
    "    print(f\"\\n{'=' * 80}\\n\")\n",
    "\n",
    "\n",
    "print(\"✓ Conversation loop implemented\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 1: Weather Query\n",
    "\n",
    "Let's test with a simple weather question. Claude should:\n",
    "1. Call `tool_search` to find weather tools\n",
    "2. Receive weather tool definitions in the result\n",
    "3. Use one of the discovered tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "================================================================================\n",
      "USER: What's the weather like in Tokyo?\n",
      "================================================================================\n",
      "\n",
      "\n",
      "--- Turn 1 ---\n",
      "\n",
      "🔧 Tool invocation: get_weather\n",
      "   Input: {\n",
      "  \"location\": \"Tokyo\"\n",
      "}\n",
      "   ✅ Mock result: {\"location\": \"Tokyo\", \"temperature\": 75, \"unit\": \"fahrenheit\", \"conditions\": \"partly cloudy\", \"humidity\": 61, \"wind_speed\": 9}\n",
      "\n",
      "--- Turn 2 ---\n",
      "\n",
      "✓ Conversation complete\n",
      "\n",
      "ASSISTANT: The weather in Tokyo is currently:\n",
      "- **Temperature:** 75°F (about 24°C)\n",
      "- **Conditions:** Partly cloudy\n",
      "- **Humidity:** 61%\n",
      "- **Wind Speed:** 9 mph\n",
      "\n",
      "It's a pleasant day with comfortable temperatures and some cloud cover!\n",
      "\n",
      "================================================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "run_tool_search_conversation(\"What's the weather like in Tokyo?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 2: Finance Query\n",
    "\n",
    "Let's try a financial calculation query that requires discovering and using finance tools:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "================================================================================\n",
      "USER: If I invest $10,000 at 5% annual interest for 10 years with monthly compounding, how much will I have?\n",
      "================================================================================\n",
      "\n",
      "\n",
      "--- Turn 1 ---\n",
      "\n",
      "🔧 Tool invocation: calculate_compound_interest\n",
      "   Input: {\n",
      "  \"principal\": 10000,\n",
      "  \"rate\": 5,\n",
      "  \"years\": 10,\n",
      "  \"frequency\": \"monthly\"\n",
      "}\n",
      "   ✅ Mock result: {\"principal\": 10000, \"rate\": 5, \"years\": 10, \"compounding_frequency\": \"monthly\", \"final_amount\": 16470.09, \"interest_earned\": 6470.09}\n",
      "\n",
      "--- Turn 2 ---\n",
      "\n",
      "✓ Conversation complete\n",
      "\n",
      "ASSISTANT: If you invest $10,000 at 5% annual interest for 10 years with monthly compounding, you will have:\n",
      "\n",
      "**Final Amount: $16,470.09**\n",
      "\n",
      "This means you'll earn **$6,470.09** in interest over the 10-year period.\n",
      "\n",
      "The monthly compounding means that interest is calculated and added to your principal every month, which allows your investment to grow faster than with annual compounding due to the effect of earning \"interest on interest\" more frequently.\n",
      "\n",
      "================================================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "run_tool_search_conversation(\n",
    "    \"If I invest $10,000 at 5% annual interest for 10 years with monthly compounding, how much will I have?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "In this cookbook, we implemented a client-side tool search system that enables Claude to work with large tool libraries efficiently. We covered:\n",
    "\n",
    "- **Semantic tool discovery**: Using embeddings to match natural language queries to relevant tools, enabling Claude to find the right capability without seeing all available tools upfront\n",
    "- **Dynamic tool loading**: Returning tool definitions in tool results using Claude's tool search feature, allowing Claude to discover and immediately use new tools mid-conversation\n",
    "- **Context optimization**: Reducing initial context from thousands of tokens (19+ tool definitions) to just the single `tool_search` definition, cutting context usage by 90%+\n",
    "\n",
    "### Applying This to Your Projects\n",
    "\n",
    "Consider tool search when:\n",
    "- You have **>20 specialized tools** and context usage becomes a concern\n",
    "- Your tool library **grows over time** and manual curation becomes impractical\n",
    "- You need to support **domain-specific APIs** with hundreds of endpoints (database operations, internal microservices, third-party integrations)\n",
    "- **Cost and latency optimization** are priorities for your application\n",
    "\n",
    "### Next Steps\n",
    "\n",
    "To take this implementation further:\n",
    "\n",
    "1. **Persist embeddings**: Cache embeddings to disk to avoid recomputing on every session, reducing startup time\n",
    "2. **Improve search quality**: Experiment with different embedding models (e.g., larger models like `all-mpnet-base-v2`) or implement hybrid search combining semantic and keyword matching (BM25)\n",
    "3. **Scale to larger libraries**: Test with hundreds or thousands of tools to see how the pattern performs at production scale\n",
    "4. **Add tool metadata**: Include usage statistics, cost information, or reliability scores in your search ranking\n",
    "5. **Implement caching**: Cache frequently used tool definitions to reduce repeated searches\n",
    "\n",
    "### Further Reading\n",
    "\n",
    "- [Claude Tool Use Guide](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) - Comprehensive guide to building with tools\n",
    "- [SentenceTransformers Documentation](https://www.sbert.net/) - Learn more about embedding models and semantic search\n",
    "- [Tool Search Tool Documentation](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#tool-search) - Official documentation on the tool search pattern"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
